import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { completable } from "@modelcontextprotocol/sdk/server/completable.js";
import { CUISINES } from "./const";
import { formatRecipesAsMarkdown } from "./formatRecipesAsMarkdown";

const server = new McpServer({
  name: "favorite-recipes",
  version: "1.0.0",
});

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main().catch((error) => {
  console.error("Server error:", error);
  process.exit(1);
});

server.registerResource(
  "recipes",
  new ResourceTemplate("file://recipes/{cuisine}", {
    list: undefined,
    complete: {
      cuisine: (value) => {
        return CUISINES.filter((cuisine) => cuisine.startsWith(value));
      },
    },
  }),
  {
    title: "特定菜系的食谱",
    description: "按菜系组织的传统食谱",
  },
  async (uri, variables, _extra) => {
    const cuisine = variables.cuisine;

    if (!CUISINES.includes(cuisine)) {
      throw new Error(`未知的菜系: ${cuisine}`);
    }

    const content = formatRecipesAsMarkdown(cuisine);
    return {
      contents: [
        {
          uri: uri.href,
          mimeType: "text/markdown",
          text: content,
        },
      ],
    };
  }
);

server.registerPrompt(
  "weekly-meal-planner",
  {
    title: "每周膳食计划器",
    description: "根据特定菜系的食谱创建每周膳食计划和购物清单",
    argsSchema: {
      cuisine: completable(z.string(), (value) => {
        return CUISINES.filter((cuisine) => cuisine.startsWith(value));
      }),
    },
  },
  async ({ cuisine }) => {
    const resourceUri = `file://recipes/${cuisine}`;
    const recipeContent = formatRecipesAsMarkdown(cuisine);

    return {
      title: `每周膳食计划器 - ${cuisine} 菜系`,
      description: `针对 ${cuisine} 菜系的每周膳食计划器`,
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `为本周规划烹饪。我已附上 ${cuisine} 菜系的食谱。
  
  请创建：
  1. 使用这些食谱制定一份 7 天的膳食计划
  2. 一份优化的购物清单，通过在多个食谱中重复使用食材来最大限度地减少浪费
  3. 每日膳食时间表，包含早餐、午餐和晚餐的具体菜肴
  4. 提高本周效率的备餐技巧
  5. 打印购物清单
  
  重点关注食谱间的食材重叠，以减少食物浪费。`,
          },
        },
        {
          role: "user",
          content: {
            type: "resource",
            resource: {
              uri: resourceUri,
              mimeType: "text/markdown",
              text: recipeContent,
            },
          },
        },
      ],
    };
  }
);
